package com.sky.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.context.BaseContext;
import com.sky.dto.OrdersPageQueryDTO;
import com.sky.dto.OrdersPaymentDTO;
import com.sky.dto.OrdersSubmitDTO;
import com.sky.entity.*;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.BaiDuUtil;
import com.sky.utils.IdWorkerUtil;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

@Service
@RequiredArgsConstructor
public class OrderServiceImpl implements OrderService {
    private  final OrderMapper orderMapper;
    private final AddressBookMapper addressBookMapper;
    private final ShoppingCartMapper shoppingCartMapper;
    private final OrderDetailMapper orderDetailMapper;
    private final UserMapper userMapper;
    private final WeChatPayUtil weChatPayUtil;
    private final BaiDuUtil baiDuUtils;
    /**
     * 用户下单
     * @param ordersSubmitDTO
     * @return
     */
    @Override
    @Transactional
    public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) {
        //1,保存订单
        //  1.1填入传过来的数据
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO,orders);

        // 1.2封装其他数据
        //1)用户ID
        Long userId = BaseContext.getCurrentId();
        orders.setUserId(userId);
        //2)订单号
        IdWorkerUtil idWorkerUtil = new IdWorkerUtil(1,1);
        long ddh = idWorkerUtil.nextId();//雪花算法生成订单号
        orders.setNumber(String.valueOf(ddh));
        //3)订单状态,下单日期,支付状态
        orders.setStatus(Orders.PENDING_PAYMENT);//1待支付
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(Orders.UN_PAID);//0未支付
        //4)配送的地址信息
        AddressBook addressBook = addressBookMapper.getAddId(ordersSubmitDTO.getAddressBookId());//获取地址
        orders.setAddressBookId(addressBook.getId());
        orders.setAddress(addressBook.getProvinceName()+addressBook.getCityName()+addressBook.getDistrictName()+addressBook.getDetail());
        orders.setPhone(addressBook.getPhone());
        orders.setConsignee(addressBook.getConsignee());

        //判断是不是超出范围
        baiDuUtils.checkOutOfRange(orders.getAddress());
        // 1.3 保存订单
        orderMapper.insertSubmitOrder(orders);

        //3,保存订单明细(购物车列表`订单ID)
        Long orderId = orders.getId();
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.findCartListByUserId(userId);
        shoppingCartList.stream().forEach( //stream流批量插入购物车商品
                shoppingCart -> {
                    OrderDetail orderDetail = new OrderDetail();
                    BeanUtils.copyProperties(shoppingCart,orderDetail);
                    orderDetail.setOrderId(orderId);
                    orderDetailMapper.addOrderDetail(orderDetail);
                }
        );
        //清空购物车
        shoppingCartMapper.DeleteShoppingCar(userId);
        //获取订单返回
        OrderSubmitVO userOrder = orderMapper.findUserOrder(orderId);
        return userOrder;
    }
    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();

        // 根据订单号查询当前用户的订单
        Orders ordersDB = orderMapper.getByNumberAndUserId(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);
    }

    /**
     * 查询历史订单
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult ViewOrderHistory(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());
        List<OrderVO> orderVOS = orderMapper.ViewOrderHistory(ordersPageQueryDTO);
        Page<OrderVO> page = (Page<OrderVO>) orderVOS;
        PageResult pageResult = PageResult.builder()
                .total(page.getTotal())
                .records(page.getResult())
                .build();

        return pageResult;
    }

    /**
     * 查询订单详情
     * @param id
     * @return
     */
    @Override
    public OrderVO IdViewOrder(String id) {
        OrderVO orderVO = orderMapper.IdViewOrder(id);
        return orderVO;
    }

    /**
     * 取消订单
     * @param id
     */
    @Override
    public void IdPutOrder(String id) {
        Integer cancelled = Orders.CANCELLED;
        orderMapper.IdPutOrder(id,cancelled);
    }

    @Override
    public void addOneOrder(String id) {
        List<OrderDetail> orderDetails = orderMapper.addOneOrder(id);
        orderDetails.stream().forEach(
                orderDetail -> {
                    ShoppingCart shoppingCart = new ShoppingCart();
                    BeanUtils.copyProperties(orderDetail,shoppingCart);
                    shoppingCart.setUserId(BaseContext.getCurrentId());
                    shoppingCart.setCreateTime(LocalDateTime.now());
                    shoppingCartMapper.addShoppingCar(shoppingCart);
                });
    }
}
